import { NextRequest, NextResponse } from 'next/server'
import { getUsers, updateUser, type StoredUser } from '@/lib/database'
import { requireAuth, withErrorHandling } from '@/lib/auth-middleware'
import { userValidation, validateInput } from '@/lib/validation'

// 获取用户资料
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json(
        { error: '缺少用户ID' },
        { status: 400 }
      )
    }

    const users = await getUsers()
    const user = users.find(u => u.id === userId)

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      )
    }

    return NextResponse.json({
      success: true,
      data: user
    })
  } catch (error) {
    console.error('获取用户资料失败:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}

// 更新用户资料
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, ...profileData } = body

    if (!userId) {
      return NextResponse.json(
        { error: '缺少用户ID' },
        { status: 400 }
      )
    }

    // 使用 Zod 验证输入数据
    const validation = validateInput(userValidation.updateProfile, profileData)
    if (!validation.success) {
      return NextResponse.json(
        { error: '输入数据无效', details: validation.errors },
        { status: 400 }
      )
    }

    const validatedData = validation.data

    // 处理网站地址 - 如果是简单域名，自动添加 https://
    let processedWebsite = validatedData.website
    if (processedWebsite && !processedWebsite.includes('://')) {
      processedWebsite = `https://${processedWebsite}`
    }

    // 准备更新数据
    const updates: Partial<StoredUser> = {
      ...validatedData,
      website: processedWebsite
    }

    // 更新用户数据
    const updatedUser = await updateUser(userId, updates)

    return NextResponse.json({
      success: true,
      message: '用户资料更新成功',
      data: updatedUser
    })

  } catch (error) {
    console.error('更新用户资料失败:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}
